package com.itlong.cloud.commons.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.app.AppCloudIntercomsVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorAuthVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorInfoVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.commons.dao.ICloudElevatorDao;
import com.itlong.cloud.commons.dao.ICloudTalkPushCloudIntercomChangeLogDao;
import com.itlong.cloud.commons.dao.IPushCloudElevatorChangeLogDao;
import com.itlong.cloud.commons.service.ICloudElevatorService;
import com.itlong.cloud.commons.service.IPushCloudElevatorChangeLogService;
import com.itlong.cloud.commons.thread.queue.process.queue.SendIotPushMessageQueue;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.property.dao.ICloudIntercomDeviceServiceDao;
import com.itlong.cloud.property.dao.IPropertyEquipDao;
import com.itlong.cloud.property.dao.IDeviceEntranceInfoDao;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      云电梯响应硬件结果业务处理接口实现类
 * </desc>
 *
 * @createDate 2018/04/03
 */
@Service
public class PushCloudElevatorChangeLogServiceImpl implements IPushCloudElevatorChangeLogService {
    private static final Logger LOG = LoggerFactory.getLogger(PushCloudElevatorChangeLogServiceImpl.class);

    @Autowired
    ICloudElevatorService iCloudElevatorService;

    @Autowired
    IPushCloudElevatorChangeLogDao iPushCloudElevatorChangeLogDao;

    @Autowired
    ICloudTalkPushCloudIntercomChangeLogDao iCloudTalkPushCloudIntercomChangeLogDao;

    @Autowired
    ICloudIntercomDeviceServiceDao iCloudIntercomDeviceServiceDao;

    @Autowired
    ICloudElevatorDao iCloudElevatorDao;

    @Autowired
    MessageSender messageSender;

    @Autowired
    RedisService redisService;

    @Autowired
    SendIotPushMessageQueue sendIotPushMessageQueue;

    @Autowired
    IPropertyEquipDao iPropertyEquipDao;
    private  ExecutorService  cachedThreadPool ;

    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;

    @PostConstruct
    public void init() {
        cachedThreadPool = Executors.newFixedThreadPool(100);
    }

    /**
     * <desc>
     *      任务调度执行同步业务指令至响应硬件结果表
     * </desc>
     *
     * @author Juguang.S
     * @createDate 2018/04/03
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void timeTaskPushCloudElevator() throws Exception {

        List<DeviceBusinessElevatorChangeLogPO> business = iPushCloudElevatorChangeLogDao.getPendingBusiness(null,null);
        if(!business.isEmpty()) {
            Set<String> projectIds = new HashSet<>();
            //获取当前需要进行业务同步的所有项目
            business.forEach(po -> {
                projectIds.add(po.getProjectId());
            });
//            for(DeviceBusinessElevatorChangeLogPO po : business){
//                projectIds.add(po.getProjectId());
//            }
            //遍历项目id，以项目为中心
            for (String projectId : projectIds) {
                Integer fullType=null;
                //查找是否有全量更新
                if (business.stream().filter(po ->
                        po.getCommandType() == CloudElevatorChangeBusinessEnum.PUSH_SERVER.getCommandType() && po.getProjectId().equals(projectId)).findFirst().isPresent()) {
                    //云电梯业务服务器地址变更 /device/login
                    fullType=CloudElevatorChangeBusinessEnum.PUSH_SERVER.getCommandType();
                }
                if (business.stream().filter(po ->
                        po.getCommandType() == CloudElevatorChangeBusinessEnum.PUSH_ROOM_FULL.getCommandType() && po.getProjectId().equals(projectId)).findFirst().isPresent()) {
                    //房间全量更新 /device/pullDeviceAuthInfo
                    fullType=CloudElevatorChangeBusinessEnum.PUSH_ROOM_FULL.getCommandType();
                }
                if (fullType!=null) {
                    //更新状态为已处理
                    this.updateFull(projectId,fullType,null);
                    continue;
                }
            }
        }
    }

    /**
     * <desc>
     *      处理推送的云电梯楼层信息
     * </desc>
     *
     * @param business 业务数据
     * @author Jiaqi.X
     * @createDate 2018/11/22
     */
    @Override
    public void setPushDeviceFloorInfo(List<DeviceBusinessElevatorChangeLogPO> business) throws IOException {
        Set<String> devices = new HashSet<>();
        Set<String> controller = new HashSet<>();
        for(DeviceBusinessElevatorChangeLogPO bu : business){
            List<String> sns = JsonUtil.decode(bu.getCommandParameter(), new TypeReference<List<String>>() {});
            for(int i = 0 ; i < sns.size() ; i++ ){
                devices.add(sns.get(i));
            }
        }
        List<PushCloudElevatorChangeLogPO> projects=new ArrayList<>();
        //将与电梯绑定的云群控器sn暂存在set容器中
        Set<String> controllerSn = new HashSet<>();
        for(String sn : devices){
            PushCloudElevatorChangeLogPO push = new PushCloudElevatorChangeLogPO();
            push.setCommandId(LogicIdUtil.bussinessId());
            //判断该电梯是否被云群控器所绑定，所绑定则将其保存至set中
            if(StringUtils.isNotEmpty(iPushCloudElevatorChangeLogDao.isBindControllerByElevator(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn)))){
               controllerSn.add(sn);
            }
            //获取电梯副盘使用状态
            Integer bracketPanel = iPushCloudElevatorChangeLogDao.getBracketPanelBySn(sn);

            CloudDeviceFloorInfoVO vo = iCloudElevatorService.getCloudDeviceFloorInfo(sn,null);
            //清空不用的字段内容
            if (bracketPanel == 0) {
                vo.setTerminalNumSlave1("");
                vo.setTerminalNumSlave2("");
            } else if (bracketPanel == 1) {
                vo.setTerminalNumSlave2("");
            }
            push.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
            push.setCommandData(JsonUtil.toJSON(vo));
            push.setSn(sn);
            push.setCommandType(PushElevatorChangeEnum.PUSH_FLOOR.getType());
            push.setStatus(DataStatusEnum.NORMAL.getType());
            push.setCommandStatus(DataStatusEnum.DELETE.getType());
            push.setCreateTime(new Date());
            push=(PushCloudElevatorChangeLogPO) StringHandlerUtil.formatString(push);
            projects.add(push);
        }
        //查询与当前电梯所绑定的云控器保存至SET容器中去重
        for(String sn : controllerSn){
            String controllerDeviceUnique = iPushCloudElevatorChangeLogDao.isBindControllerByElevator(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
            String controllerDeviceSn = controllerDeviceUnique.substring(0,8)+"00000"+controllerDeviceUnique.substring(10,13);
            controller.add(controllerDeviceSn);
        }

        for(String sn : controller){
            PushCloudElevatorChangeLogPO push = new PushCloudElevatorChangeLogPO();
            push.setCommandId(LogicIdUtil.bussinessId());
            CloudDeviceFloorInfoVO vo = iCloudElevatorService.getCloudDeviceFloorInfo(sn,"128");
            push.setDeviceUnique(StringHandlerUtil.getControllerDeviceUniqueBySn(sn));
            push.setCommandData(JsonUtil.toJSON(vo));
            push.setSn(sn);
            push.setCommandType(PushElevatorChangeEnum.PUSH_FLOOR.getType());
            push.setStatus(DataStatusEnum.NORMAL.getType());
            push.setCommandStatus(DataStatusEnum.DELETE.getType());
            push.setCreateTime(new Date());
            push=(PushCloudElevatorChangeLogPO) StringHandlerUtil.formatString(push);
            projects.add(push);
        }

        if (!projects.isEmpty()) {
            iPushCloudElevatorChangeLogDao.batchSave(projects);
            this.sendIotMessage(projects);
        }
    }

    /**
     * <desc>
     *      全量更新/云电梯业务服务器地址变更
     * </desc>
     *
     * @param projectId 项目id
     * @author Juguang.S
     * @createDate 2018/04/03
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void updateFull(String projectId,Integer type,String params){
        try {
            List<PushCloudElevatorChangeLogPO> full =new ArrayList<>();
            List<CloudElevatorByProjectIdVO> clouds = iPushCloudElevatorChangeLogDao.getCloudElevatorByProjectId(projectId,null);
            String iotFlag = StringHandlerUtil.getNullOrStringForObject(JsonUtil.toObject(params,HashMap.class).get("iotFlag"));
            for(CloudElevatorByProjectIdVO cloud : clouds) {
                PushCloudElevatorChangeLogPO push = new PushCloudElevatorChangeLogPO();
                push.setCommandId(LogicIdUtil.bussinessId());
                push.setDeviceUnique(cloud.getDeviceUnique());
                push.setSn(cloud.getSn());
                push.setCommandType(PushElevatorChangeEnum.PUSH_FULL.getType());
                if (type == CloudElevatorChangeBusinessEnum.PUSH_SERVER.getCommandType()) {
                    push.setCommandData("/device/login");
                    if(StringUtils.isNotBlank(iotFlag)) {
                        push.setIotFlag(Integer.valueOf(iotFlag));
                    }
                } else {
                    push.setCommandData("/device/elevator/pullDeviceAuthInfo");
                    if(StringUtils.isNotBlank(iotFlag)) {
                        push.setIotFlag(Integer.valueOf(iotFlag));
                    }
                }
                push.setStatus(DataStatusEnum.NORMAL.getType());
                push.setCommandStatus(DataStatusEnum.DELETE.getType());
                push.setCreateTime(new Date());
                full.add(push);
            }
            if(!full.isEmpty()){
                if(!full.isEmpty()) {
                    iPushCloudElevatorChangeLogDao.batchSave(full);
                    this.sendIotMessage(full);
                }
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表全量更新执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + "："+e);
        }
    }

    /**
     * <desc>
     *      处理推送硬件响应项目信息
     * </desc>
     *
     * @param business 业务数据
     * @author Juguang.S
     * @createDate 2018/04/03
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushProject(List<DeviceBusinessElevatorChangeLogPO> business) {
        try {
            List<PushCloudElevatorChangeLogPO> projects=new ArrayList<>();
            Set<String> pro = new HashSet<>();
            for (DeviceBusinessElevatorChangeLogPO bus : business) {
                if (pro.add(bus.getProjectId())) {
                    Map<String,Object> params = JsonUtil.toObject(bus.getCommandParameter(),HashMap.class);
                    String deviceUnique = StringHandlerUtil.getNullOrStringForObject(params.get("deviceUnique"));
                    //根据项目ID获取项目下的云电梯设备和云群控器设备
                    List<CloudElevatorByProjectIdVO> clouds = iPushCloudElevatorChangeLogDao.getCloudElevatorByProjectId(business.get(0).getProjectId(),deviceUnique);
                    CloudElevatorPushProjectCommanDataVO vo = iPushCloudElevatorChangeLogDao.getProjectById(business.get(0).getProjectId());
                    //处理云电梯和云群控器相关推送指令
                    List<CloudIntercomDeviceVO.PropertyValue> list = iCloudIntercomDeviceServiceDao.getPropertyInfo(bus.getProjectId(),2);
                    if (list.size() == 0) {
                        list = new ArrayList<>();
                        list.add(new CloudIntercomDeviceVO.PropertyValue());
                    }
                    for(CloudIntercomDeviceVO.PropertyValue pv: list){
                        pv.setDay(pv.getDay() == null ? 0 : pv.getDay());
                        pv.setPointOut(pv.getPointOut() == null ? 0 : pv.getPointOut());
                    }
                    vo.setDeploys(list);
                    //查询电梯绑定摄像头相关参数
                    DeviceAiCameraInfoVO aiCameraInfoVO = iCloudElevatorDao.getAiCameraInfoByElevatorDeviceUnique(deviceUnique);
                    if(aiCameraInfoVO!=null){
                        Map<String,Object> map = new HashMap<>();
                        map.put("deviceIp",aiCameraInfoVO.getCameraIp());
                        map.put("isOpenAlarm",aiCameraInfoVO.getAlarmStatus());
                        map.put("isUploadPicture",aiCameraInfoVO.getUploadStatus());
                        vo.setWebCam(map);
                    }
                    for (CloudElevatorByProjectIdVO cloud : clouds) {
                        if(cloud.getDeviceUnique().substring(8,9).equals("1")){
                            DeviceAiCameraInfoVO cameraInfoVO = iCloudElevatorDao.getAiCameraInfoByElevatorDeviceUnique(cloud.getDeviceUnique());
                            if(cameraInfoVO!=null){
                                Map<String,Object> map = new HashMap<>();
                                map.put("deviceIp",cameraInfoVO.getCameraIp());
                                map.put("isOpenAlarm",cameraInfoVO.getAlarmStatus());
                                map.put("isUploadPicture",cameraInfoVO.getUploadStatus());
                                vo.setWebCam(map);
                            }
                        }
                        //添加设备名称属性
                        vo.setDeviceName(cloud.getDeviceName());
                        vo.setEquipMode(cloud.getEquipMode());
                        vo.setBindList(cloud.getBindList());
                        //查询项目信息
                        PushCloudElevatorChangeLogPO po = new PushCloudElevatorChangeLogPO();
                        po.setCommandType(PushElevatorChangeEnum.PUSH_PROJECT.getType());
                        po.setCommandId(LogicIdUtil.bussinessId());
                        po.setCommandData(JsonUtil.toJSON(vo));
                        po.setDeviceUnique(cloud.getDeviceUnique());
                        po.setSn(cloud.getSn());
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCommandStatus(DataStatusEnum.DELETE.getType());
                        po.setCreateTime(new Date());
                        po=(PushCloudElevatorChangeLogPO) StringHandlerUtil.formatString(po);
                        projects.add(po);
                    }
                    if(clouds==null||clouds.size()==0){
                        //此处为了兼容处理 变更了摄像头所绑定电梯的配置后，只需要向单个电梯设备推送指令，并不需要向项目下所有设备推送指令
                        CloudElevatorByProjectIdVO cloudElevatorByDeviceUnique = iPushCloudElevatorChangeLogDao.getCloudElevatorByDeviceUnique(deviceUnique);
                        vo.setDeviceName(cloudElevatorByDeviceUnique.getDeviceName());
                        vo.setEquipMode(cloudElevatorByDeviceUnique.getEquipMode());
                        vo.setBindList(cloudElevatorByDeviceUnique.getBindList());
                        //查询项目信息
                        PushCloudElevatorChangeLogPO po = new PushCloudElevatorChangeLogPO();
                        po.setCommandType(PushElevatorChangeEnum.PUSH_PROJECT.getType());
                        po.setCommandId(LogicIdUtil.bussinessId());
                        po.setCommandData(JsonUtil.toJSON(vo));
                        po.setDeviceUnique(cloudElevatorByDeviceUnique.getDeviceUnique());
                        po.setSn(cloudElevatorByDeviceUnique.getSn());
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCommandStatus(DataStatusEnum.DELETE.getType());
                        po.setCreateTime(new Date());
                        po=(PushCloudElevatorChangeLogPO) StringHandlerUtil.formatString(po);
                        projects.add(po);
                    }
                }
                break;
            }
            if (!projects.isEmpty()) {
                iPushCloudElevatorChangeLogDao.batchSave(projects);
                this.sendIotMessage(projects);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表项目信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+":"+e);
        }
    }

    /**
     * <desc>
     *      处理推送硬件响应设备信息
     * </desc>
     *
     * @param business 业务数据
     * @author Juguang.S
     * @createDate 2018/04/03
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushDevice(List<DeviceBusinessElevatorChangeLogPO> business){
        try {
            List<PushCloudElevatorChangeLogPO> devices = new ArrayList<>();
            Map<String, Object> deviceMap = new HashMap<>();
            for (DeviceBusinessElevatorChangeLogPO bus : business) {
                List<Map<String, Object>> list =  JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {});
                Set<String> deviceUniques = new HashSet<>();
                list.forEach(deviceUnique -> {
                    deviceUniques.add(deviceUnique.get("deviceUnique").toString());
                });
                for (String deviceUnique : deviceUniques) {
                    Set<String> deviceSet = deviceMap.get(deviceUnique) == null ? new HashSet<>() : (Set<String>) deviceMap.get(deviceUnique);
                    if (deviceSet.add(deviceUnique)) {
                        deviceMap.put(deviceUnique, deviceSet);
                        //判断是否已有相同设备的推送消息
                        PushCloudElevatorChangeLogPO ownedPush = new PushCloudElevatorChangeLogPO();
                        ownedPush.setCommandType(PushElevatorChangeEnum.PUSH_FULL.getType());
                        ownedPush.setCommandId(LogicIdUtil.bussinessId());
                        ownedPush.setStatus(DataStatusEnum.NORMAL.getType());
                        ownedPush.setCommandStatus(DataStatusEnum.DELETE.getType());
                        ownedPush.setCreateTime(new Date());
                        //查询设备详情
                        Map<String, Object> deviceInfo = null;
                        if(deviceUnique.substring(8,9).equals("5")){
                            deviceInfo = iPushCloudElevatorChangeLogDao.getPushCloudControllerDeviceInfo(deviceUnique);
                        }else{
                            deviceInfo = iPushCloudElevatorChangeLogDao.getPushDeviceInfo(deviceUnique);
                        }
                        ownedPush.setDeviceUnique(deviceUnique);
                        if(deviceInfo != null){
                            ownedPush.setSn(deviceInfo.get("sn").toString());
                        }
                        ownedPush.setCommandData("/device/login");
                        devices.add(ownedPush);
                    }
                }
            }
            if (!devices.isEmpty()) {
                iPushCloudElevatorChangeLogDao.batchSave(devices);
                this.sendIotMessage(devices);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表设备信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ":"+e);
        }
    }

    /**
     * <desc>
     *      处理推送设备响应固定密码信息
     * </desc>
     *
     * @param business 业务数据
     * @author Juguang.S
     * @createDate 2018/04/04
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushFixedPassword(List<DeviceBusinessElevatorChangeLogPO> business) {
        try {
            List<PushCloudElevatorChangeLogPO> passwords = new ArrayList<>();
            Set<String> buildSet = new HashSet<>();
            Set<String> roomSet = new HashSet<>();
            for (DeviceBusinessElevatorChangeLogPO bus : business) {
                List<Map<String,Object>> rms = JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {});
                for(Map<String,Object> map : rms){
                    String buildId = map.get("buildId").toString();
                    String unitId = map.get("unitId").toString();
                    String roomId = map.get("roomId").toString();
                    buildSet.add(buildId);
                    roomSet.add(roomId);
                }
                String buidStr = null;
                List<CloudElevatorByBuildIdVO> cloudElevatorByBuildIdVOList = iPushCloudElevatorChangeLogDao.getCloudElevatorByBuildId(buildSet.toArray(new String[buildSet.size()]));
                for(CloudElevatorByBuildIdVO vo : cloudElevatorByBuildIdVOList){
                    PushCloudElevatorChangeLogPO ownedPush = new PushCloudElevatorChangeLogPO();
                    ownedPush.setDeviceUnique(vo.getDeviceUnique());
                    ownedPush.setCommandId(LogicIdUtil.bussinessId());
                    ownedPush.setSn(vo.getSn());
                    ownedPush.setStatus(DataStatusEnum.NORMAL.getType());
                    ownedPush.setCommandStatus(DataStatusEnum.DELETE.getType());
                    ownedPush.setCreateTime(new Date());
                    ownedPush.setCommandType(PushElevatorChangeEnum.PUSH_ROOM_PWD.getType());
                    //根据roomId去查找room的信息，赋值于commandData
                    PushRoomCommanDataByCloudElevatorVO pushRoomCommanDataByCloudElevatorVO;
                    List<PushRoomCommanDataByCloudElevatorVO> voList = new ArrayList<>();
                    for(String roomId : roomSet){
                        int mark = 1;
                        //查询设备下的房间id集合
                        List<Map<String,Object>> roomList =  iPushCloudElevatorChangeLogDao.getRoomInfoByElevator(vo.getDeviceUnique());
                        for(Map<String,Object> map : roomList){
                            String roomIdStr = map.get("roomId").toString();
                            String liftDoorType = map.get("liftDoorType").toString();
                            if(roomId.equals(roomIdStr) && vo.getLiftDoorType().equals(liftDoorType)){
                                mark=2;
                            }else{
                                continue;
                            }
                        }
                        if(mark==1){
                            continue;
                        }
                        pushRoomCommanDataByCloudElevatorVO = iPushCloudElevatorChangeLogDao.getRoomInfo(roomId,vo.getSn().substring(0,8));
                         if(pushRoomCommanDataByCloudElevatorVO!=null){
                            pushRoomCommanDataByCloudElevatorVO=(PushRoomCommanDataByCloudElevatorVO)StringHandlerUtil.formatString(pushRoomCommanDataByCloudElevatorVO);
                            voList.add(pushRoomCommanDataByCloudElevatorVO);
                        }else{
                             RoomInfoPO roomInfo = iPushCloudElevatorChangeLogDao.getRoomInfoByRoomId(roomId);
                             if(roomInfo != null) {
                                 PushRoomCommanDataByCloudElevatorVO elevatorVO = new PushRoomCommanDataByCloudElevatorVO();
                                 elevatorVO.setOpenPwd("");
                                 elevatorVO.setRoomId(roomId);
                                 elevatorVO.setRoomNum(roomInfo.getRoomNum());
                                 elevatorVO.setStatus(roomInfo.getStatus());
                                 elevatorVO.setSoftCardNums(roomInfo.getSoftCardNums());
                                 elevatorVO.setIdCardNums(roomInfo.getHardCardNums());
                                 elevatorVO.setFingerNums(roomInfo.getFingerNums());
                                 elevatorVO.setArrearsTime(roomInfo.getArrearsTime());
                                 elevatorVO = (PushRoomCommanDataByCloudElevatorVO) StringHandlerUtil.formatString(elevatorVO);
                                 voList.add(elevatorVO);
                             }
                         }
                    }
                    if(voList!=null && voList.size() > 0){
                        ownedPush.setCommandData(JsonUtil.toJSON(voList));
                        passwords.add(ownedPush);
                    }
                }
            }
            if (!passwords.isEmpty()) {
                iPushCloudElevatorChangeLogDao.batchSave(passwords);
                this.sendIotMessage(passwords);
            }
        } catch (Exception e) {
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果固定密码信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+"："+e);
        }
    }

    /**
     * <desc>
     *      处理推送设备项目信息变更
     * </desc>
     *
     * @param business 业务数据
     * @author Juguang.S
     * @createDate 2018/04/08
     */
    @Override
    public void setPushDeviceProjectInfo(List<DeviceBusinessElevatorChangeLogPO> business){
        try {
            List<PushCloudElevatorChangeLogPO> deviceProjectList = new ArrayList<>();
            Set<String> deviceUniqueSet = new HashSet<>();
            for (DeviceBusinessElevatorChangeLogPO bus : business) {
                JSONObject commandParameter = JSON.parseObject(bus.getCommandParameter());
                String deviceUnique = (String) commandParameter.get("deviceUnique");
                //判断是否有相同deviceUnique
                if(deviceUniqueSet.add(deviceUnique)){
                    //查询设备详情
                    Map<String, Object> deviceInfo;
                    if(deviceUnique.substring(8,9).equals("5")){
                        deviceInfo = iPushCloudElevatorChangeLogDao.getPushCloudControllerDeviceInfo(deviceUnique);
                    }else{
                        deviceInfo = iPushCloudElevatorChangeLogDao.getPushDeviceInfo(deviceUnique);
                    }
                    PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                    pushVO.setCommandType(PushElevatorChangeEnum.PUSH_PROJECT.getType());
                    pushVO.setCommandId(LogicIdUtil.bussinessId());
                    pushVO.setCreateTime(new Date());
                    pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                    pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                    pushVO.setSn(deviceInfo.get("sn").toString());
                    pushVO.setDeviceUnique(deviceUnique);
                    CloudElevatorPushProjectCommanDataVO vo = iPushCloudElevatorChangeLogDao.getProjectById(business.get(0).getProjectId());
                    vo.setDeviceName(deviceInfo.get("deviceName").toString());
                    if(!deviceUnique.substring(8,9).equals("5")) {
                        vo.setEquipMode(deviceInfo.get("equipMode") == null ? 1 : Integer.parseInt(deviceInfo.get("equipMode").toString()));
                    }
                    pushVO.setCommandData(JsonUtil.toJSON(vo));
                    deviceProjectList.add(pushVO);
                }
            }
            if (!deviceProjectList.isEmpty()) {
                iPushCloudElevatorChangeLogDao.batchSave(deviceProjectList);
                this.sendIotMessage(deviceProjectList);
            }
        } catch (Exception e) {
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果设备项目信息变更执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + "：" + e);
        }
    }

    /**
     * <desc>
     *      处理推送设备项目信息变更
     * </desc>
     *
     * @param business 业务数据
     * @author Qiang.S
     * @createDate 2019/04/26
     */
    public void setPushUserProject(List<DeviceBusinessElevatorChangeLogPO> business, Integer type){
        try {
            List<PushCloudElevatorChangeLogPO> users = new ArrayList<>();
            for(DeviceBusinessElevatorChangeLogPO bus : business) {
                if (StringUtils.isNotBlank(bus.getCommandParameter()) && !bus.getCommandParameter().equals("[]")) {
                    //根据type 解析map的结构
                    Map<String, Object> map = new HashMap<>();
                    if (type == 1) {
                        Map<String, Object> projectMap = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
                        map.put(projectMap.get("userId").toString(), projectMap.get("userId"));
                    } else {
                        List<Map<String, Object>> userRoom = JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {
                        });
                        userRoom.forEach(user->{
                            if (map.get(user.get("userId").toString()) == null) {
                                map.put(user.get("userId").toString(), user.get("userId").toString());
                            }
                        });
                        for (String userId : map.keySet()) {
                            Set<String> roomSet = new HashSet<>();
                            userRoom.forEach(ur -> {
                                if (ur.get("userId").toString().equals(userId)) {
                                    roomSet.add(ur.get("roomId").toString());
                                }
                            });
                            map.put(userId, roomSet.toArray(new String[roomSet.size()]));
                        }
                    }
                    for (String userId : map.keySet()) {
                        //获取项目下有权限的所有云电梯设备信息
                        List<AppCloudIntercomsVO> clouds = iPushCloudElevatorChangeLogDao.getUserClouds(userId, bus.getProjectId());
                        if (clouds == null || clouds.isEmpty()) {
                            continue;
                        }
                        for (AppCloudIntercomsVO cloud : clouds) {
                            List<PushUserElevatorCommandDataVO> voList;
                            //判断是否已有相同设备的推送消息
                            PushCloudElevatorChangeLogPO ownedPush;
                            try {
                                ownedPush = users.stream().filter(roomUser -> roomUser.getDeviceUnique().equals(cloud.getDeviceUnique())).findFirst().get();
                            } catch (NoSuchElementException e) {
                                ownedPush = null;
                            }
                            //获取用户房间号
                            String[] roomIds;
                            if (type == 1) {
                                roomIds = StringHandlerUtil.splitString(cloud.getRoomIds());
                            } else {
                                roomIds = (String[]) map.get(userId);
                            }
                            //如果没有房间
                            if (roomIds.length < 1) {
                                continue;
                            }
                            if (ownedPush != null) {
                                voList = (List<PushUserElevatorCommandDataVO>) JsonUtil.toListObject(ownedPush.getCommandData(), ArrayList.class, PushUserElevatorCommandDataVO .class);
                            } else {
                                ownedPush = new PushCloudElevatorChangeLogPO();
                                ownedPush.setCommandId(LogicIdUtil.bussinessId());
                                ownedPush.setDeviceUnique(cloud.getDeviceUnique());
                                ownedPush.setCreateTime(new Date());
                                ownedPush.setCommandStatus(0);
                                ownedPush.setStatus(DataStatusEnum.NORMAL.getType());
                                ownedPush.setCommandType(PushElevatorChangeEnum.PUSH_USER.getType());
                                //获取设备sn
                                ownedPush.setSn(iPushCloudElevatorChangeLogDao.getSnByDeviceUnique(cloud.getDeviceUnique()));
                                users.add(ownedPush);
                                voList = new ArrayList<>();
                            }
                            if (roomIds.length > 0) {
                                for (String roomId : roomIds) {
                                    //判断在需要更新的设备中是否有相同的用户房间信息
                                    Optional<PushUserElevatorCommandDataVO> optUser = voList.stream().filter(pu -> pu.getUserId().equals(userId) && pu.getRoomId().equals(roomId)).findFirst();
                                    if (!optUser.isPresent()) {
                                        PushUserElevatorCommandDataVO pushUser = new PushUserElevatorCommandDataVO();
                                        pushUser.setUserId(userId);
                                        pushUser.setRoomId(roomId);
                                        if (iPushCloudElevatorChangeLogDao.checkDeviceInRoom(cloud.getDeviceUnique(), roomId) > 0) {
                                            //查询用户的项目信息
                                            Map<String, Object> projectInfo;
                                            try {
                                                projectInfo = iCloudTalkPushCloudIntercomChangeLogDao.getPushUserProjectInfo(pushUser.getUserId(), bus.getProjectId(), pushUser.getRoomId());
                                            } catch (Exception e) {
                                                LOG.error(String.format("【同步业务指令至响应硬件结果表用户信息执行失败：用户与项目信息有多条】 用户Id:%s 项目id:%s", pushUser.getUserId(), bus.getProjectId()));
                                                continue;
                                            }
                                            if(projectInfo!=null) {
                                                pushUser.setUserName(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("userName")));
                                                pushUser.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("idcardKey")));
                                                pushUser.setIsLoss(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("isLoss")));
                                                pushUser.setRoomNum(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("roomNum")));
                                                pushUser.setStartTime(null);
                                                pushUser.setEndTime(null);
                                                pushUser.setVisitorType(0);
                                                //组装用户信息vip标识符
                                                if (StringHandlerUtil.getNullOrStringForObject(projectInfo.get("userLabel"))==null){
                                                    pushUser.setIsVip(0);
                                                }else {
                                                    pushUser.setIsVip(Arrays.asList(projectInfo.get("userLabel").toString().split(",")).contains("1")?1:0);
                                                }
                                                //组装常用楼层和常用公共楼层
                                               pushUser.setCommonFloor(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("commonFloor")));
                                               pushUser.setPublicFloor(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("publicFloor")));


                                                String userRoomStatus = projectInfo.get("userRoomStatus").toString();
                                                String userProjectStatus = projectInfo.get("userProjectStatus").toString();
                                                String projectStatus = projectInfo.get("projectStatus").toString();
                                                String status = projectInfo.get("status").toString();
                                                if (userRoomStatus.equals("2") && userProjectStatus.equals("1") && status.equals("1") && projectStatus.equals("1")) {
                                                    pushUser.setStatus("1");
                                                } else {
                                                    pushUser.setStatus("0");
                                                }
                                                pushUser = (PushUserElevatorCommandDataVO) StringHandlerUtil.formatString(pushUser);
                                                voList.add(pushUser);
                                            }
                                        }
                                    }
                                }
                            }
                            ownedPush.setCommandData(JsonUtil.toJSON(voList));
                        }
                    }
                    for (String userId : map.keySet()) {
                        SimpleDateFormat sdf =new SimpleDateFormat("yyMMddHHmmss");
                        SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //访客的时候
                        //获取访客信息 以及 房间下的云电梯设备
                        List<PushCloudVisitorInfoDeviceVO> list = iPushCloudElevatorChangeLogDao.getVisitorDeviceInfo(userId);
                        for (PushCloudVisitorInfoDeviceVO vo : list) {
                            List<PushUserElevatorCommandDataVO> voList = new ArrayList<>();
                            PushCloudElevatorChangeLogPO ownedPush = new PushCloudElevatorChangeLogPO();
                            ownedPush.setCommandId(LogicIdUtil.bussinessId());
                            ownedPush.setDeviceUnique(vo.getDeviceUnique());
                            ownedPush.setSn(vo.getSn());
                            ownedPush.setCreateTime(new Date());
                            ownedPush.setCommandStatus(0);
                            ownedPush.setStatus(DataStatusEnum.NORMAL.getType());
                            ownedPush.setCommandType(PushElevatorChangeEnum.PUSH_USER.getType());
                            ownedPush.setSn(vo.getSn());

                            PushUserElevatorCommandDataVO pushUser = new PushUserElevatorCommandDataVO();
                            pushUser.setUserId(vo.getVFaceId() == null ? "" : vo.getVFaceId());
                            pushUser.setUserName(vo.getVisitorName() == null ? "" : vo.getVisitorName());
                            Date date =sdf2.parse(vo.getStartTime());
                            pushUser.setStartTime(sdf.format(date));
                            date =sdf2.parse(vo.getEndTime());
                            pushUser.setEndTime(sdf.format(date));
                            pushUser.setRoomId(vo.getRoomId());
                            pushUser.setIdcardKey(vo.getIdcardKey() == null ? "" : vo.getIdcardKey());
                            pushUser.setIsLoss("");
                            pushUser.setVisitorType(1);
                            pushUser.setStatus(vo.getStatus());
                            pushUser.setRoomNum(vo.getRoomNum());
                            //组装访客vip标签
                            pushUser.setIsVip(0);



                            voList.add(pushUser);
                            ownedPush.setCommandData(JsonUtil.toJSON(voList));
                            users.add(ownedPush);
                        }
                    }
                }
            }
            for (int i=users.size()-1;i>=0;i--) {
                PushCloudElevatorChangeLogPO po = users.get(i);
                if (po.getCommandData() == null || "[]".equals(po.getCommandData())) {
                    users.remove(i);
                }
            }
            if (!users.isEmpty()) {
                iPushCloudElevatorChangeLogDao.batchSave(users);
                this.sendIotMessage(users);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new DataAccessException("【定时任务】同步云电梯业务指令至响应硬件结果设备项目信息变更执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+"："+e);
        }
    }

    /**
     * <desc>
     *      处理推送电梯黑名单信息变更
     * </desc>
     *
     * @param business
     * @author Jiaqi.X
     * @createDate 2019/10/15
     */
    public void setBlackList(List<DeviceBusinessElevatorChangeLogPO> business) throws IOException {
        List<PushCloudElevatorChangeLogPO> pushBlackList = new ArrayList<>();
        for (DeviceBusinessElevatorChangeLogPO bus : business) {
            Map<String, Object> roomMap = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
            String roomId = roomMap.get("roomId").toString();
            String projectId = roomMap.get("projectId").toString();
            //获取房间下的电梯设备
            Map<String,Object> address = iPropertyEquipDao.getAddressByRoomId(roomId);
            List<CloudElevatorVO> elevatorList = iPropertyEquipDao.getElevatorListByAddress(address);
            //查询项目的预警次数
            Integer warningTimes = iCloudElevatorDao.getWarningTimesByProjectId(projectId);
            for(CloudElevatorVO vo : elevatorList){
                List<BlackListVO> blackList = new ArrayList<>();
                Set<String> userIds = new HashSet<>();
                //地址黑名单
                List<UserBlackInfoVO> users = iCloudElevatorDao.getBlackUserInfosByRoomId(roomId,projectId);
                for (UserBlackInfoVO user : users) {
                    if(userIds.add(user.getUid()+user.getRoomNo())) {
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringHandlerUtil.autlSupply(8, user.getUid(), "0"));
                        blackListVO.setType(1);
                        if ((user.getChargeMode()!=null && user.getChargeMode() == 1) && ((user.getUsableCount() == null || user.getUsableCount() <= 0)) || (StringUtils.isNotEmpty(user.getUserProjectStatus()) && user.getUserProjectStatus().equals("0"))) {
                            blackListVO.setStatus(1);
                        }else if((user.getChargeMode()!=null && user.getChargeMode() == 1) && ((user.getUsableCount() != null && user.getUsableCount() <= warningTimes))){
                            blackListVO.setStatus(2);
                        } else {
                            blackListVO.setStatus(0);
                        }
                        blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0").toUpperCase());
                        blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                        blackList.add(blackListVO);
                    }
                }

                //获取卡黑名单
                List<UserBlackInfoVO> cardInfos = iCloudElevatorDao.getBlackCardByRoomId(roomId,projectId);
                if(cardInfos!=null && !cardInfos.isEmpty()){
                    for(UserBlackInfoVO cardInfo : cardInfos){
                        if(StringUtils.isEmpty(cardInfo.getSoftCardNums())){
                            continue;
                        }
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringUtils.isBlank(cardInfo.getSoftCardNums())?"":cardInfo.getSoftCardNums());
                        blackListVO.setType(2);
                        if ((cardInfo.getChargeMode()!=null && cardInfo.getChargeMode() == 1) && (cardInfo.getUsableCount() == null || cardInfo.getUsableCount() <= 0)) {
                            blackListVO.setStatus(1);
                        }else if((cardInfo.getChargeMode()!=null && cardInfo.getChargeMode() == 1) && ((cardInfo.getUsableCount() != null && cardInfo.getUsableCount() <= warningTimes))){
                            blackListVO.setStatus(2);
                        } else {
                            blackListVO.setStatus(0);
                        }
                        blackListVO.setBatch(0);
                        blackListVO.setRoomNo(roomId);
                        blackList.add(blackListVO);
                    }
                }else{
                    //此处处理房间绑定卡时，所绑房间无次数时，须向设备下发黑名单
                    List<UserBlackInfoVO> cardInfoNoCounts = iCloudElevatorDao.getBlackCardNoCountByRoomId(roomId,projectId);
                    for(UserBlackInfoVO cardInfoNocounts : cardInfoNoCounts){
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringUtils.isBlank(cardInfoNocounts.getSoftCardNums())?"":cardInfoNocounts.getSoftCardNums());
                        blackListVO.setType(2);
                        blackListVO.setStatus(1);
                        blackListVO.setBatch(0);
                        blackListVO.setRoomNo(roomId);
                        blackList.add(blackListVO);
                    }
                }

                //临时权限黑名单
                List<UserBlackInfoVO> tempUsers = iCloudElevatorDao.getTempBlackInfosByRoomId(roomId,projectId,
                        Integer.valueOf(StringHandlerUtil.getDeviceIdByDeviceUnique(vo.getDeviceUnique())));
                tempUsers.stream().forEach(user->{
                    if(userIds.add(user.getUid()+user.getRoomNo())) {
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(user.getUid());
                        blackListVO.setType(1);
                        if ((user.getChargeMode()!=null && user.getChargeMode() == 1) && ((user.getUsableCount() == null || user.getUsableCount() <= 0) || (StringUtils.isNotEmpty(user.getUserProjectStatus()) && user.getUserProjectStatus().equals("0")))) {
                            blackListVO.setStatus(1);
                        }else if((user.getChargeMode()!=null && user.getChargeMode() == 1) && ((user.getUsableCount() != null && user.getUsableCount() <= warningTimes))){
                            blackListVO.setStatus(2);
                        }else{
                            blackListVO.setStatus(0);
                        }
                        blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0").toUpperCase());
                        blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                        blackList.add(blackListVO);
                    }
                });
                if(!blackList.isEmpty()) {
                    PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                    pushVO.setCommandType(PushElevatorChangeEnum.PUSH_BLACK.getType());
                    pushVO.setCommandId(LogicIdUtil.bussinessId());
                    pushVO.setCreateTime(new Date());
                    pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                    pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                    pushVO.setDeviceUnique(vo.getDeviceUnique());
                    pushVO.setSn(StringHandlerUtil.getSnByDeviceUnique(vo.getDeviceUnique()));
                    pushVO.setCommandData(JsonUtil.toJSON(blackList));
                    //为了去重未消费的指令，在保存前需查下数据库是否有相同指令，若有则不进行保存
//                    if(iCloudElevatorDao.getIsSameData(vo.getDeviceUnique(),JsonUtil.toJSON(blackList))==0){
                    pushBlackList.add(pushVO);
//                    }
                }
            }
        }
        if (!pushBlackList.isEmpty()) {
            iPushCloudElevatorChangeLogDao.batchSave(pushBlackList);
            this.sendIotMessage(pushBlackList);
        }
    }

    /**
     * <desc>
     *      处理推送用户临时权限
     * </desc>
     *
     * @param business 业务数据
     * @author Jiaqi.X
     * @createDate 2019/09/14
     */
    public void setPushTempAuth(List<DeviceBusinessElevatorChangeLogPO> business) throws IOException {
        List<PushCloudElevatorChangeLogPO> deviceProjectList = new ArrayList<>();
        for (DeviceBusinessElevatorChangeLogPO bus : business) {
            Map<String,Object> map = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
            String elevatorAuth = StringHandlerUtil.getNullOrStringForObject(map.get("elevatorAuth"));
            String[] oldElevatorDeviceIds = StringHandlerUtil.splitString(elevatorAuth);
            List<String> oldDeviceIdList = Arrays.asList(oldElevatorDeviceIds);
            if(map.get("type").toString().equals("1")) {
                int delete = 0;
                List<Map<String, Object>> auths = iCloudElevatorDao.getPushTempAuths(map.get("projectId").toString(), map.get("userId").toString());
                if(auths.isEmpty()){
                    if(map.get("elevatorAuthList")!=null) {
                        delete = 1;
                        List<Map<String,Object>> elevatorAuthList = JsonUtil.decode(map.get("elevatorAuthList").toString(), new TypeReference<List<Map<String, Object>>>() {});
                        if(!elevatorAuthList.isEmpty()) {
                            auths.add(elevatorAuthList.get(0));
                        }
                    }
                }
                //此处处理去重指令逻辑处理
                Set<String> set = null;
                if(auths.size()>1){
                    set = new HashSet<>();
                }
                for (Map<String, Object> auth : auths) {
                    ElevatorTempAuthVO tempVO = new ElevatorTempAuthVO();
                    tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(auth.get("userId")));
                    tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(auth.get("userName")));
                    tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(auth.get("idcardKey")));
                    tempVO.setVisitorType(auth.get("visitorType") != null ? Integer.valueOf(auth.get("visitorType").toString()) : null);
                    tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(auth.get("isLoss")));
                    tempVO.setStatus(StringHandlerUtil.getNullOrStringForObject(auth.get("status")));
                    //获取电梯的授权设备信息
                    List<AppElevatorAuthDTO> elevatorAuths;
                    if(delete == 0) {
                        elevatorAuths = iCloudElevatorDao.getPushFloorAuth(auth.get("userId").toString(), map.get("projectId").toString());
                    }else{
                        elevatorAuths = JsonUtil.decode(map.get("elevatorFloorAuthList").toString(), new TypeReference<List<AppElevatorAuthDTO>>() {});
                    }
                    AppElevatorAuthVO tempElevatorAuth = StringHandlerUtil.convertElevatorAuth(elevatorAuths);
                    List<AppElevatorInfoVO> tempAuths = tempElevatorAuth.getElevatorAuth();
                    for (AppElevatorInfoVO tempAuth : tempAuths) {
                        if(delete == 0 && StringUtils.isNotBlank(tempAuth.getLiveFloor())) {
                            tempVO.setFloor(iCloudElevatorDao.getLogicFloorByNaturalFloor(StringHandlerUtil.splitString(tempAuth.getLiveFloor()),
                                    map.get("projectId").toString() + "1" + tempAuth.getDeviceId()));
                        }else{
                            tempVO.setStatus("0");
                        }
                        tempVO = (ElevatorTempAuthVO)StringHandlerUtil.formatString(tempVO);
                        List<ElevatorTempAuthVO> list = new ArrayList<>();
                        list.add(tempVO);
                        if(auths.size()>1){
                            if(set.contains(list.toString()+map.get("projectId").toString() + "1" + tempAuth.getDeviceId())){
                                break;
                            }else{
                                set.add(list.toString()+map.get("projectId").toString() + "1" + tempAuth.getDeviceId());
                            }
                        }
                        PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                        pushVO.setCommandType(PushElevatorChangeEnum.PUSH_TEMP.getType());
                        pushVO.setCommandId(LogicIdUtil.bussinessId());
                        pushVO.setCreateTime(new Date());
                        pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                        pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                        pushVO.setSn(StringHandlerUtil.getSnByDeviceUnique(map.get("projectId").toString() + "1" + tempAuth.getDeviceId()));
                        pushVO.setDeviceUnique(map.get("projectId").toString() + "1" + tempAuth.getDeviceId());
                        pushVO.setCommandData(JsonUtil.toJSON(list));
                        deviceProjectList.add(pushVO);
                        //此处查询下该用户类型为临时权限有没未消费的指令，如有则将状态改为已消费
                        iCloudElevatorDao.updateUntreatedCommand(tempVO.getUserId(),pushVO.getSn());
                    }
                    //取消勾选的临时权限
                    if(!oldDeviceIdList.isEmpty()){
                        for(String oldDeviceId : oldDeviceIdList){
                            if(!tempAuths.stream().filter(temp->temp.getDeviceId().equals(oldDeviceId)).findFirst().isPresent()){
                                ElevatorTempAuthVO oldTempVO = new ElevatorTempAuthVO();
                                BeanUtils.copyProperties(tempVO, oldTempVO);
                                oldTempVO.setStatus("0");
                                oldTempVO.setFloor("");
                                List<ElevatorTempAuthVO> list = new ArrayList<>();
                                list.add(oldTempVO);
                                PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                                pushVO.setCommandType(PushElevatorChangeEnum.PUSH_TEMP.getType());
                                pushVO.setCommandId(LogicIdUtil.bussinessId());
                                pushVO.setCreateTime(new Date());
                                pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                                pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                                pushVO.setSn(StringHandlerUtil.getSnByDeviceUnique(map.get("projectId").toString() + "1" + oldDeviceId));
                                pushVO.setDeviceUnique(map.get("projectId").toString() + "1" + oldDeviceId);
                                pushVO.setCommandData(JsonUtil.toJSON(list));
                                deviceProjectList.add(pushVO);
                            }
                        }
                    }
                }
                //如果取消的为最后的临时授权权限
                if(auths.isEmpty()&&!oldDeviceIdList.isEmpty()){
                    for(String oldDeviceId : oldDeviceIdList){
                        Map<String,Object> userInfo = iCloudElevatorDao.getPushTempUserInfo(map.get("projectId").toString(),map.get("userId").toString());
                        ElevatorTempAuthVO tempVO = new ElevatorTempAuthVO();
                        tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userId")));
                        tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userName")));
                        tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(userInfo.get("idcardKey")));
                        tempVO.setVisitorType(userInfo.get("visitorType") != null ? Integer.valueOf(userInfo.get("visitorType").toString()) : null);
                        tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(userInfo.get("isLoss")));
                        tempVO.setStatus("0");
                        tempVO.setFloor("");
                        List<ElevatorTempAuthVO> list = new ArrayList<>();
                        list.add(tempVO);
                        PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                        pushVO.setCommandType(PushElevatorChangeEnum.PUSH_TEMP.getType());
                        pushVO.setCommandId(LogicIdUtil.bussinessId());
                        pushVO.setCreateTime(new Date());
                        pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                        pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                        pushVO.setSn(StringHandlerUtil.getSnByDeviceUnique(map.get("projectId").toString() + "1" + oldDeviceId));
                        pushVO.setDeviceUnique(map.get("projectId").toString() + "1" + oldDeviceId);
                        pushVO.setCommandData(JsonUtil.toJSON(list));
                        deviceProjectList.add(pushVO);
                    }
                }
            }else{
                //获取访客
                DeviceTempVisitorVO visitor = iDeviceEntranceInfoDao.getVisitorsByVisitorId(map.get("userId").toString());
                Set<String> deviceUniques = new HashSet<>();
                if(StringUtils.isNotBlank(visitor.getTempAuthDeviceUnique())){
                    for(String deviceUnique:StringHandlerUtil.splitString(visitor.getTempAuthDeviceUnique())){
                        if(deviceUnique.substring(8,9).equals("1")){
                            deviceUniques.add(deviceUnique);
                        }
                    }
                }
                for(String deviceUnique : deviceUniques) {
                    ElevatorTempAuthVO tempVO = new ElevatorTempAuthVO();
                    BeanUtils.copyProperties(visitor, tempVO);
                    if (StringUtils.isNotBlank(visitor.getFrontElevatorAuth())) {
                        Map<String, Object> frontList = JsonUtil.toObject(visitor.getFrontElevatorAuth(), HashMap.class);
                        Set<String> fronts = new HashSet<>();
                        for (String key : frontList.keySet()) {
                            if (key.equals(StringHandlerUtil.getDeviceIdByDeviceUnique(deviceUnique))) {
                                String[] floor = StringHandlerUtil.splitString(frontList.get(key).toString());
                                for (String f : floor) {
                                    fronts.add(f);
                                }
                            }
                        }
                        if(!fronts.isEmpty()) {
                            tempVO.setFloor(String.join(",", fronts));
                            tempVO.setFloor(iCloudElevatorDao.getLogicFloorByNaturalFloor(StringHandlerUtil.splitString(tempVO.getFloor()), deviceUnique));
                        }
                    }
                    if (StringUtils.isNotBlank(visitor.getBackElevatorAuth())) {
                        Map<String, Object> backList = JsonUtil.toObject(visitor.getBackElevatorAuth(), HashMap.class);
                        Set<String> backs = new HashSet<>();
                        for (String key : backList.keySet()) {
                            if (key.equals(StringHandlerUtil.getDeviceIdByDeviceUnique(deviceUnique))) {
                                String[] floor = StringHandlerUtil.splitString(backList.get(key).toString());
                                for (String f : floor) {
                                    backs.add(f);
                                }
                            }
                        }
                        if(!backs.isEmpty()) {
                            tempVO.setFloor(String.join(",", backs));
                            tempVO.setFloor(iCloudElevatorDao.getLogicFloorByNaturalFloor(StringHandlerUtil.splitString(tempVO.getFloor()), deviceUnique));
                        }
                    }
                    tempVO = (ElevatorTempAuthVO)StringHandlerUtil.formatString(tempVO);
                    List<ElevatorTempAuthVO> list = new ArrayList<>();
                    list.add(tempVO);
                    PushCloudElevatorChangeLogPO pushVO = new PushCloudElevatorChangeLogPO();
                    pushVO.setCommandType(PushElevatorChangeEnum.PUSH_TEMP.getType());
                    pushVO.setCommandId(LogicIdUtil.bussinessId());
                    pushVO.setCreateTime(new Date());
                    pushVO.setStatus(DataStatusEnum.NORMAL.getType());
                    pushVO.setCommandStatus(DataStatusEnum.DELETE.getType());
                    pushVO.setDeviceUnique(deviceUnique);
                    pushVO.setSn(StringHandlerUtil.getSnByDeviceUnique(deviceUnique));
                    pushVO.setCommandData(JsonUtil.toJSON(list));
                    deviceProjectList.add(pushVO);
                }
            }
        }
        if (!deviceProjectList.isEmpty()) {
            iPushCloudElevatorChangeLogDao.batchSave(deviceProjectList);
            this.sendIotMessage(deviceProjectList);
        }
    }


    /**
     * <desc>
     *      处理推送设备指令转换为iot指令
     * </desc>
     *
     * @param list 指令内容
     * @author Qiang.S
     * @createDate 2019/07/04
     */
    private void sendIotMessage (List<PushCloudElevatorChangeLogPO> list) {
        try {
            List<PushCloudElevatorChangeLogPO> listElevator = new ArrayList<>();
            List<PushCloudElevatorChangeLogPO> listController = new ArrayList<>();
            //过滤离线设备
            for (int i = list.size() - 1; i >= 0; i--) {
                if (list.get(i).getDeviceUnique().substring(8, 9).equals("5")) {//群控器
                    if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY + list.get(i).getDeviceUnique()))) {
                        listController.add(list.get(i));
                    }
                } else {//云电梯
                    if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY + list.get(i).getDeviceUnique()))) {
                        listElevator.add(list.get(i));
                    }
                }
            }
            if (listElevator.size() > 0) {//云电梯
                //取得版本和iotkey
                ProductTypePO productKey = iPushCloudElevatorChangeLogDao.getElevatorVersonIotkey(listElevator.get(0).getDeviceUnique());
                //拼接所有deviceUnique取得
                for (PushCloudElevatorChangeLogPO po : listElevator) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" +  po.getDeviceUnique()  + (productKey.getIotVersion() == 1 ? "/user" : "") + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(),"itlong","2001",0,po.getCommandType().toString(),1,po.getIotFlag());
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
            if (listController.size() > 0) {//群控器
                //取得版本和iotkey
                ProductTypePO productKey = iPushCloudElevatorChangeLogDao.getElevatorVersonIotkey(listController.get(0).getDeviceUnique());
                //iot指令准备
                for (PushCloudElevatorChangeLogPO po : listController) {
                    //LOG.info("群控器:"+po.getDeviceUnique());
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" +  po.getDeviceUnique()  + (productKey.getIotVersion() == 1 ? "/user" : "") + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(),"itlong","2001",0,po.getCommandType().toString(),1,po.getIotFlag());
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
